package com.alogic.markdown.xscript;

import com.alogic.html.xscript.HTML;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * Markdown文档
 *
 * @version 1.6.12.58 [20200113]
 */
public class MDWriter extends HTML {
    public MDWriter(String tag, Logiclet p) {
        super(tag, p);

        registerModule("m-line",Line.class);
        registerModule("m-table",MDTable.class);
    }

    /**
     * 行
     */
    public static class Line extends AbstractLogiclet{
        /**
         * 上下文id
         */
        protected String pid = "$h-conf";

        protected String $text;

        public Line(String tag, Logiclet p) {
            super(tag, p);
        }

        @Override
        public void configure(Properties p){
            super.configure(p);
            pid = PropertiesConstants.getString(p, "pid", pid,true);
            $text = PropertiesConstants.getRaw(p,"t","");
        }

        @Override
        protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
            StringBuffer content = ctx.getObject(pid);
            if (content == null){
                throw new BaseException("core.e1001","It must be in a h-conf context,check your script.");
            }

            String text = PropertiesConstants.transform(ctx, $text, "");
            if (StringUtils.isNotEmpty(text)){
                content.append('\n').append(text);
            }else{
                content.append("\n");
            }
        }
    }
}
